package com.sxl.main;

import com.googlecode.aviator.AviatorEvaluator;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 简单公式解析器
 * @ClassName: com.sxl.main.Evaluate.java
 * @author: songxulin
 * @date :  2020-11-19 20:24
 * @version V1.0
 */
public class Evaluate {
    public static void main(String[] args) {
        Map<String, Object> param = new HashMap<>();
        param.put("a",1);
        param.put("b",2);
        Object execute = AviatorEvaluator.execute("a>0", param);
        Stack<String> ops  = new Stack<String>();
        Stack<Double> vals = new Stack<Double>();
        String[] strs = "( 1+ ( ( 2 + 3 ) * ( 4 * 5 ) ) )".split(" ");
        int i = 0;
        while (i<strs.length) {
            String s = strs[i];
            if      (s.equals("("))               ;
            else if (s.equals("+"))    ops.push(s);
            else if (s.equals("-"))    ops.push(s);
            else if (s.equals("*"))    ops.push(s);
            else if (s.equals("/"))    ops.push(s);
            else if (s.equals("sqrt")) ops.push(s);
            else if (s.equals(")")) {
                String op = ops.pop();
                double v = vals.pop();
                if      (op.equals("+"))    v = vals.pop() + v;
                else if (op.equals("-"))    v = vals.pop() - v;
                else if (op.equals("*"))    v = vals.pop() * v;
                else if (op.equals("/"))    v = vals.pop() / v;
                else if (op.equals("sqrt")) v = Math.sqrt(v);
                vals.push(v);
            }
            else vals.push(Double.parseDouble(s));
            i++;
        }
        System.out.println(vals.pop());
    }

}
